package com.drop.dao.impl;

import com.drop.dao.OrderDao;
import com.drop.entity.Order;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by 陈东一 on 2017/9/24 15:25
 */
@Repository
public class OrderDaoImpl implements OrderDao{
	private Log log = LogFactory.getLog(this.getClass());

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}


	@Override
	public Boolean insertOrder(int userId, float sumMoney, int shipId ,String time, int state) throws Exception{
		String sql = "INSERT INTO `order` (userId,sumMoney,shipId,orderTime,state)  VALUES ('"+userId+"','"+sumMoney+"','"+shipId+"','"+time+"','"+state+"') ; ";
		log.info(sql);
		return getSession().createSQLQuery(sql).executeUpdate() > 0 ;
	}

	@Override
	public Boolean insertChildOrder(int orderId, List<String> goodsId, List<Float> money, List<String> num) {
		StringBuilder sql = new StringBuilder("INSERT INTO `childorder` (orderId,goodsId,money,quantity)  VALUES ");
		for(int i=0;i<goodsId.size();i++){
			if(i==0) {
				sql.append("('" + orderId + "','" + goodsId.get(i) + "','" + money.get(i) + "','" + num.get(i) + "')");
			}else{
				sql.append(" , ('" + orderId + "','" + goodsId.get(i) + "','" + money.get(i) + "','" + num.get(i) + "')");
			}
		}

		log.info(sql.toString());
		return getSession().createSQLQuery(sql.toString()).executeUpdate() > 0 ;
	}

	@Override
	public Order getOrder(int userId, String time) throws Exception {
		String hql = "from com.drop.entity.Order c where c.user.userId = ? and c.orderTime = ?";
		return (Order) getSession().createQuery(hql).setParameter(0,userId).setParameter(1,time
		).uniqueResult();
	}

	@Override
	public Boolean updateState(int id, String state ,String address) throws Exception {
		String sql = " update  `order` set state = '"+state+"' , address = '"+address+"' where orderId = '"+id+"'; ";
		log.info(sql);
		return getSession().createSQLQuery(sql).executeUpdate() > 0 ;
	}

	@Override
	public Boolean updateState(String ids, int state) throws Exception {
		String sql = " update  `order` set state = '"+state+"'  where orderId in ("+ids+"); ";
		log.info(sql);
		return getSession().createSQLQuery(sql).executeUpdate() > 0 ;
	}
}
